/*
 * Copyright 2013 Ramon Ordiales Plaza
 * Use una copia de FastMessage.exe en el directorio de GitBlit
 */
import com.gitblit.GitBlit
import com.gitblit.Keys
import com.gitblit.models.RepositoryModel
import com.gitblit.models.TeamModel
import com.gitblit.models.UserModel
import com.gitblit.utils.JGitUtils
import java.text.SimpleDateFormat
import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.lib.Config
import org.eclipse.jgit.revwalk.RevCommit
import org.eclipse.jgit.transport.ReceiveCommand
import org.eclipse.jgit.transport.ReceiveCommand.Result
import org.slf4j.Logger

logger.info("sendfastmsg hook triggered by ${user.username} for ${repository.name}")

Repository r = gitblit.getRepository(repository.name)

Config config = r.getConfig()
def mailinglist = config.getString('hooks', null, 'mailinglist')

def toAddresses = []

if (mailinglist != null) {
    def addrs = mailinglist.split(/(,|\s)/)
    toAddresses.addAll(addrs)
}

toAddresses.addAll(GitBlit.getStrings(Keys.mail.mailingLists))
	
def teams = gitblit.getRepositoryTeams(repository)
for (team in teams) {
    TeamModel model = gitblit.getTeamModel(team)
    if (model.mailingLists) {
        toAddresses.addAll(model.mailingLists)
    }
}

toAddresses.addAll(repository.mailingLists)
def tofinal=toAddresses.join(";")
r.close()

def sout = new StringBuffer(), serr = new StringBuffer()
def proc = "c:\\gitblit\\Fastmessage.exe GitBlit ${tofinal} ${repository.name}".execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(3000)
logger.info("Exec: c:\\gitblit\\Fastmessage.exe GitBlit ${tofinal} ${repository.name}")
println "out> $sout err> $serr"
logger.info("hecho")
